package com.clementheliou.cheliou.business.technical.i18n.impl;

import static org.apache.commons.lang3.StringUtils.EMPTY;
import static org.apache.commons.lang3.StringUtils.isEmpty;

import java.util.Locale;
import java.util.ResourceBundle;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.MessageSourceResourceBundle;
import org.springframework.stereotype.Service;

import com.clementheliou.cheliou.business.technical.i18n.I18nTechnicalService;

/**
 * Implementation of the application internationalization. Message source is
 * injected by Spring and must be available in the application context. The web
 * presentation layer is responsible of its supply to preserv the service
 * independency.
 * 
 * @author Clément HELIOU (clement.heliou@gmail.com)
 * @see {@link I18nTechnicalService};
 * @see {@link Service}.
 * @since 1.0
 */
@Service
public class I18nSpringMessageSourceTechnicalService implements I18nTechnicalService {

	/**
	 * The message source provided by the web presentation layer.
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @see {@link MessageSource}.
	 * @since 1.0
	 */
	@Autowired
	private MessageSource messageSource;

	/**
	 * <p>
	 * {@inheritDoc}
	 * </p>
	 * <p>
	 * The resulting bundle is a {@link MessageSourceResourceBundle}, based on
	 * the given locale. Note that this bundle doesn't have a parent one.
	 * </p>
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @since 1.0
	 */
	@Override
	public ResourceBundle getAsResourceBundle(final Locale locale) {
		return new MessageSourceResourceBundle(messageSource, locale);
	}

	/**
	 * <p>
	 * {@inheritDoc}
	 * </p>
	 * <p>
	 * If the key is null or empty, an empty value will be returned.
	 * </p>
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @see {@link LocaleContextHolder}.
	 * @since 1.0
	 */
	@Override
	public String getTranslation(String key, Locale locale) {
		if (!isEmpty(key)) {
			return messageSource.getMessage(key, null, locale);
		}
		return EMPTY;
	}

}
